#define _GUN_SOURCE
#include "daemon_sub_process.h"


sub_process_t *daemon_sub_process_init(char *sub_cmd)
{
    // 创建子进程结构体
    sub_process_t *sub_process = (sub_process_t *)malloc(sizeof(sub_process_t));
    // 初始化子进程结构体
    sub_process->sub_cmd = malloc(strlen(sub_cmd) + 1);
    strcpy(sub_process->sub_cmd, sub_cmd);
    sub_process->pid = -1;
    sub_process->fail_count = 0;

    return sub_process;
}

// 检查并启动子进程
int daemon_sub_process_check_and_start(sub_process_t *sub_process)
{
    // 检查子进程的生死 pid != -1曾经活过 waitpid != -1 还活着
    int status;
    if (sub_process->pid != -1 && waitpid(sub_process->pid,&status,WNOHANG) != -1)
    {
        return 0; // 说明程序正在运行 无需处理
    }
    
    // 之后部分都是子进程已死 u是不是横死 waitpid status != 0 则c子进程是横死
    // failed_count++ 如果超过阈值则进行重启设备
    if (status != 0)
    {
        sub_process->fail_count++;
        if (sub_process->fail_count > MAX_FAILED_COUNT)
        {
            // 重启设备
            // system("reboot");
            reboot(RB_AUTOBOOT);
        }
    }
    // 拉活 开始启动fork
    pid_t pid = fork();
    if (pid > 0)
    {
        // 父进程
        sub_process->pid = pid;
        log_info("子进程启动成功 pid=%d",pid);
    }
    else
    {
        // 子进程
        char *args[3] = {EXE_NAME,sub_process->sub_cmd,NULL};
        char *env[1] = {NULL};
        int ret = execve(EXE_NAME,args,env);
        if (ret == -1)
        {
            log_error("子进程启动失败");
            exit(EXIT_FAILURE);
        }
        
    }
    return 0;
}

// 结束子进程
void daemon_sub_process_stop(sub_process_t *sub_process)
{
    kill(sub_process->pid,SIGTERM);
    waitpid(sub_process->pid,NULL,WUNTRACED);
    free(sub_process);
    // sub_process->pid = -1;
    // sub_process->fail_count = 0;
    log_info("子进程结束成功");
}